package com.kolakcc.swf;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.kolakcc.loljclient.util.FileSystem;

public class SWFExtractor {
	private static String[][] files = { { "ImagePack_items.swf", "items", "png" }, 
						 				{ "ImagePack_buddyIcons.swf", "buddyIcons", "jpg" },
						 				{ "ImagePack_spells.swf", "spells", "png" },
						 				{ "ImagePack_masteryIcons.swf", "masteries", "png" } };
	// file, destination folder, file type
	
	//TODO: use a JFileChooser
	public SWFExtractor() throws Exception {
		//check swfdump
		File swfdump = new File("C:\\Program Files (x86)\\SWFTools\\swfdump.exe");
		if (!swfdump.exists()) swfdump = new File("C:\\Program Files\\SWFTools\\swfdump.exe");
		if (!swfdump.exists()) swfdump = new File("swfdump");
		if (!swfdump.exists()) throw new Exception("SWFdump not found.");
		String swfdumpLocation = swfdump.getParent() + File.separatorChar;
		for (String[] file : files) {
			Process p = new ProcessBuilder(swfdumpLocation + "swfdump", FileSystem.getRADSFile("assets/imagePacks/"+file[0]).getAbsolutePath()).start();
			java.util.Scanner s = new java.util.Scanner(p.getInputStream()).useDelimiter("\n");
			String output;
			while (true) {
				if (!s.hasNext()) break;
				output = s.next();
				Pattern pat = Pattern.compile(".*exports (.+?) as.*__e_(.*)\"");
				Matcher m = pat.matcher(output);
				if (m.find()) {
					ProcessBuilder pb = new ProcessBuilder(swfdumpLocation + "swfextract", FileSystem.getRADSFile("assets/imagePacks/"+file[0]).getAbsolutePath(), "-"+file[2].charAt(0),m.group(1), "--output", file[1]+File.separatorChar+m.group(2)+"."+file[2]);
					System.out.println(pb.command());
					pb.directory(FileSystem.getFile("app://img/"));
					pb.start();
				}
			}
		    s.close();
		}
	}
}
